#include "wifi_board.h"
#include "audio_codecs/no_audio_codec.h"
#include "display/lcd_display.h"
#include "application.h"
#include "config.h"
#include "i2c_device.h"
#include "iot/thing_manager.h"
#include "axp202.h" 

#include <esp_log.h>
#include <driver/i2c_master.h>
#include <wifi_station.h>
#include <esp_lcd_panel_io.h>
#include <esp_lcd_panel_ops.h>
#include <esp_lcd_ili9341.h>
#include <esp_timer.h>
#include <esp_lcd_touch_ft5x06.h>
#include <esp_lvgl_port.h>
#include <lvgl.h>
#include "custom_display.h"
#include "led/single_led.h"

#define TAG "LilygoWatchV3"

#define AXP202_I2C_ADDR  0x35

#define BIT_MASK(ch) (1 << (ch))

#define AXP202_ON 1
#define AXP202_OFF 0


enum {
    AXP202_EXTEN = 0,
    AXP202_DCDC3 = 1,
    AXP202_LDO2 = 2,
    AXP202_LDO4 = 3,
    AXP202_DCDC2 = 4,
    AXP202_LDO3 = 6,
    AXP202_OUTPUT_MAX,
};

typedef enum {
    AXP202_LDO4_1250MV,
    AXP202_LDO4_1300MV,
    AXP202_LDO4_1400MV,
    AXP202_LDO4_1500MV,
    AXP202_LDO4_1600MV,
    AXP202_LDO4_1700MV,
    AXP202_LDO4_1800MV,
    AXP202_LDO4_1900MV,
    AXP202_LDO4_2000MV,
    AXP202_LDO4_2500MV,
    AXP202_LDO4_2700MV,
    AXP202_LDO4_2800MV,
    AXP202_LDO4_3000MV,
    AXP202_LDO4_3100MV,
    AXP202_LDO4_3200MV,
    AXP202_LDO4_3300MV,
    AXP202_LDO4_MAX,
} axp_ldo4_table_t;


class Pmic : public Axp202 {
public:
    // Power Init
    Pmic(i2c_master_bus_handle_t i2c_bus, uint8_t addr) : Axp202(i2c_bus, addr) {
        // WriteReg(0xB8, 0x80);  // 清除
        // delay(10);
        // WriteReg(0xB8, 0x20);  // 启用
    }

    void setLDO3Mode(uint8_t mode)
    {
        uint8_t val = ReadReg(0x29);
        if (mode) {
            val |= BIT_MASK(7);
        } else {
            val &= (~BIT_MASK(7));
        }
        WriteReg(0x29, val);
    }

    void setLDO4Voltage(axp_ldo4_table_t param) {
        uint8_t val = ReadReg(0x28);
        val &= 0xF0;
        val |= param;
        WriteReg(0x28, val);
    }

    void setPowerOutPut(uint8_t ch, bool en) {
        uint8_t data;
        // 确保输出寄存器（OUTPUT REGISTER）不全为零
        do {
            data = ReadReg(0x12);
        } while (data == 0);

        // 根据启用或禁用状态更新寄存器值
        if (en) {
            data |= (1 << ch);
        } else {
            data &= ~(1 << ch);
        }
        data |= BIT_MASK(3); // 强制打开DCDC3

        // 写入更新后的寄存器值
        WriteReg(0x12, data);
    }

};

class LilygoWatchV3Board : public WifiBoard {
private:
    i2c_master_bus_handle_t i2c_bus_;
    i2c_master_bus_handle_t apx_i2c_bus_;
    Pmic* pmic_;
    // Ft6336* ft6336_;
    LcdDisplay* display_;
    esp_timer_handle_t touchpad_timer_;

    void InitializeI2c() {
        // Initialize I2C peripheral
        i2c_master_bus_config_t i2c_bus_cfg = {
            .i2c_port = TP_I2C_PORT,
            .sda_io_num = TP_PIN_NUM_SDA,
            .scl_io_num = TP_PIN_NUM_SCL,
            .clk_source = I2C_CLK_SRC_DEFAULT,
            .glitch_ignore_cnt = 7,
            .intr_priority = 0,
            .trans_queue_depth = 0,
            .flags = {
                .enable_internal_pullup = 1,
            },
        };
        ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_bus_cfg, &i2c_bus_));

        i2c_master_bus_config_t apx_bus_cfg = {
            .i2c_port = APX_I2C_PORT,
            .sda_io_num = APX_PIN_NUM_SDA,
            .scl_io_num = APX_PIN_NUM_SCL,
            .clk_source = I2C_CLK_SRC_DEFAULT,
            .glitch_ignore_cnt = 7,
            .intr_priority = 0,
            .trans_queue_depth = 0,
            .flags = {
                .enable_internal_pullup = 1,
            },
        };
        ESP_ERROR_CHECK(i2c_new_master_bus(&apx_bus_cfg, &apx_i2c_bus_));
        ESP_LOGI(TAG, "I2C initialized"); 
    }

    void InitializeAxp202() {
        ESP_LOGI(TAG, "Init AXP202");
        pmic_ = new Pmic(apx_i2c_bus_, AXP202_I2C_ADDR);
    }

    void InitializeTouch()
    {
        esp_lcd_touch_handle_t tp;
        esp_lcd_touch_config_t tp_cfg = {
            .x_max = DISPLAY_WIDTH,
            .y_max = DISPLAY_HEIGHT,
            .rst_gpio_num = TP_PIN_NUM_RST, // Shared with LCD reset
            .int_gpio_num = TP_PIN_NUM_INT, 
            .levels = {
                .reset = 0,
                .interrupt = 0,
            },
            .flags = {
                .swap_xy = DISPLAY_SWAP_XY,
                .mirror_x = DISPLAY_MIRROR_X,
                .mirror_y = !DISPLAY_MIRROR_Y,
            },
        };
        esp_lcd_panel_io_handle_t tp_io_handle = NULL;
        esp_lcd_panel_io_i2c_config_t tp_io_config = ESP_LCD_TOUCH_IO_I2C_FT5x06_CONFIG();
        tp_io_config.scl_speed_hz = 400000;

        esp_lcd_new_panel_io_i2c(i2c_bus_, &tp_io_config, &tp_io_handle);
        esp_lcd_touch_new_i2c_ft5x06(tp_io_handle, &tp_cfg, &tp);
        assert(tp);

        /* Add touch input (for selected screen) */
        const lvgl_port_touch_cfg_t touch_cfg = {
            .disp = lv_display_get_default(), 
            .handle = tp,
        };

        lvgl_port_add_touch(&touch_cfg);
    }

    void InitializeSpi() {
        spi_bus_config_t buscfg = {};
        buscfg.mosi_io_num = DISPLAY_MOSI_PIN;
        buscfg.miso_io_num = GPIO_NUM_NC;
        buscfg.sclk_io_num = DISPLAY_CLK_PIN;
        buscfg.quadwp_io_num = GPIO_NUM_NC;
        buscfg.quadhd_io_num = GPIO_NUM_NC;
        buscfg.max_transfer_sz = DISPLAY_WIDTH * DISPLAY_HEIGHT * sizeof(uint16_t);
        ESP_ERROR_CHECK(spi_bus_initialize(SPI3_HOST, &buscfg, SPI_DMA_CH_AUTO));
    }

    void InitializesSt7789Display() {
        ESP_LOGI(TAG, "Init ST7789");

        esp_lcd_panel_io_handle_t panel_io = nullptr;
        esp_lcd_panel_handle_t panel = nullptr;

        ESP_LOGD(TAG, "Install panel IO");
        esp_lcd_panel_io_spi_config_t io_config = {};
        io_config.cs_gpio_num = DISPLAY_CS_PIN;
        io_config.dc_gpio_num = DISPLAY_DC_PIN;
        io_config.spi_mode = 2;
        io_config.pclk_hz = 40 * 1000 * 1000;
        io_config.trans_queue_depth = 10;
        io_config.lcd_cmd_bits = 8;
        io_config.lcd_param_bits = 8;
        ESP_ERROR_CHECK(esp_lcd_new_panel_io_spi(SPI3_HOST, &io_config, &panel_io));

        ESP_LOGD(TAG, "Install LCD driver");
        esp_lcd_panel_dev_config_t panel_config = {};
        panel_config.reset_gpio_num = DISPLAY_RST_PIN;
        panel_config.rgb_ele_order = LCD_RGB_ELEMENT_ORDER_RGB;
        panel_config.bits_per_pixel = 16;
        ESP_ERROR_CHECK(esp_lcd_new_panel_st7789(panel_io, &panel_config, &panel));
        
        esp_lcd_panel_reset(panel);

        esp_lcd_panel_init(panel);
        esp_lcd_panel_invert_color(panel, true);
        esp_lcd_panel_swap_xy(panel, DISPLAY_SWAP_XY);
        esp_lcd_panel_mirror(panel, DISPLAY_MIRROR_X, DISPLAY_MIRROR_Y);

        display_ = new CustomLcdDisplay(panel_io, panel,
            DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_OFFSET_X, DISPLAY_OFFSET_Y, DISPLAY_MIRROR_X, DISPLAY_MIRROR_Y, DISPLAY_SWAP_XY);
    }

    // 物联网初始化，添加对 AI 可见设备
    void InitializeIot() {
        auto& thing_manager = iot::ThingManager::GetInstance();
        thing_manager.AddThing(iot::CreateThing("Speaker"));
        thing_manager.AddThing(iot::CreateThing("Screen"));
        thing_manager.AddThing(iot::CreateThing("Battery"));
        thing_manager.AddThing(iot::CreateThing("BiliFans"));
        thing_manager.AddThing(iot::CreateThing("AlarmIot"));
        thing_manager.AddThing(iot::CreateThing("Motor"));
    }

public:
    LilygoWatchV3Board() {
        InitializeI2c();
        InitializeAxp202();

        pmic_->setPowerOutPut(AXP202_LDO2, AXP202_ON);
        // pmic_->setLDO3Mode(AXP202_ON);
        // pmic_->setPowerOutPut(AXP202_LDO3, AXP202_ON);
        pmic_->setLDO4Voltage(AXP202_LDO4_3300MV);
        pmic_->setPowerOutPut(AXP202_LDO4, AXP202_ON);
        
        InitializeSpi();
        InitializesSt7789Display();
        InitializeTouch();
        InitializeIot();
        if (DISPLAY_BACKLIGHT_PIN != GPIO_NUM_NC) {
            GetBacklight()->RestoreBrightness();
        }
    }

    virtual AudioCodec* GetAudioCodec() override {
        static NoAudioCodecSimplexPdm audio_codec(AUDIO_INPUT_SAMPLE_RATE, AUDIO_OUTPUT_SAMPLE_RATE,
            AUDIO_I2S_SPK_GPIO_BCLK, AUDIO_I2S_SPK_GPIO_LRCK, AUDIO_I2S_SPK_GPIO_DOUT, AUDIO_I2S_MIC_GPIO_WS, AUDIO_I2S_MIC_GPIO_DIN);
        return &audio_codec;
    }

    virtual Display* GetDisplay() override {
        return display_;
    }

    virtual bool GetBatteryLevel(int &level, bool& charging, bool& discharging) override {
        static bool last_discharging = false;
        charging = pmic_->IsCharging();
        discharging = pmic_->IsDischarging();
        if (discharging != last_discharging) {
            last_discharging = discharging;
        }

        level = pmic_->GetBatteryLevel();
        return true;
    }

    virtual Backlight* GetBacklight() override {
        if (DISPLAY_BACKLIGHT_PIN != GPIO_NUM_NC) {
            static PwmBacklight backlight(DISPLAY_BACKLIGHT_PIN, DISPLAY_BACKLIGHT_OUTPUT_INVERT);
            return &backlight;
        }
        return nullptr;
    }
    
    // virtual Led* GetLed() override {
    //     // static GpioLed led(MOTOR_PIN);
    //     static SingleLed led(MOTOR_PIN);
    //     return &led;
    // }
};

DECLARE_BOARD(LilygoWatchV3Board);
